package cn.ipokerface.api;

import cn.ipokerface.api.parser.Formatter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by       PokerFace
 * Create Date      2019-12-07.
 * Email:           <a href="mailto:214888341@163.com">214888341@163.com</a>
 * Version          1.0.0
 * <p>
 * Description:
 */
public class Generator {


    private CoreContext context;

    private Generator(CoreContext context){
        this.context = context;
    }





    /**
     *  Execute generate task under context...
     *  {@link CoreContext} and {@link CoreContext.Builder}
     *
     * @param context generate context
     */
    public static void generate(CoreContext context){
        try{
            new Generator(context).execute();
        }catch (IOException e){
            e.printStackTrace();
        }
    }


    /**
     *  Execute generate goal.
     *  steps:
     *  1. init configuration
     *  2. scan target package.
     *  3. generate document.
     *
     *
     */
    private void execute() throws IOException{

        // init configuration

        // scan target package.
        PackageScanner scanner = new PackageScanner(context);

        ConfigurationHolder holder = scanner.scan();


        File file = prepareFile();

        Formatter generateFormatter = context.getFormatter();

        if (generateFormatter == null || generateFormatter.getParser() == null) throw new IllegalArgumentException("Formatter is not settle....");

        OutputStream outputStream = new FileOutputStream(file);

        generateFormatter.getParser().parse(holder, outputStream);

        if (outputStream != null) outputStream.close();

    }


    private File prepareFile() throws IOException {
        String path = context.getOutputFile();


        File targetFile = new File(path);

        // create Dirs
        targetFile.mkdirs();

        if (targetFile.exists()) {
            targetFile.delete();
        }

        return targetFile;
    }
}
